package com.ucar.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore.MediaColumns;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

public class Utils {
	
	public static DisplayMetrics getDisplayMetrics(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		wm.getDefaultDisplay().getMetrics(dm);
		
		return dm;
	}
	
	/**
	 * 获取当前app包信息对象.
	 * 
	 * @param context
	 * @return
	 * @throws NameNotFoundException
	 */
	private static PackageInfo getCurrentAppPackageInfo(Context context) {
		try {
			PackageManager manager = context.getPackageManager();
			String packageName = context.getPackageName();
			PackageInfo info = manager.getPackageInfo(packageName, 0);
			return info;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取当前app的版本号.
	 * 
	 * @param context
	 * @return
	 */
	public static int getCurrentAppVersionCode(Context context) {
		PackageInfo info = getCurrentAppPackageInfo(context);
		int versionCode = info.versionCode;
		return versionCode;
	}

	/**
	 * 获取当前app的版本名字.
	 * 
	 * @param context
	 * @return
	 */
	public static String getCurrentAppVersionName(Context context) {
		PackageInfo info = getCurrentAppPackageInfo(context);
		String version = info.versionName;
		return version;
	}

	/**
	 * 获取手机的imei.
	 * 
	 * @param context
	 * @return
	 */
	public static String getDeviceId(Context context) {
		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = telephonyManager.getDeviceId();
		return imei;
	}

	public static List<String> getTagsList(String originalText) {
		if (originalText == null || originalText.equals("")) {
			return null;
		}
		List<String> tags = new ArrayList<String>();
		int indexOfComma = originalText.indexOf(',');
		String tag;
		while (indexOfComma != -1) {
			tag = originalText.substring(0, indexOfComma);
			tags.add(tag);

			originalText = originalText.substring(indexOfComma + 1);
			indexOfComma = originalText.indexOf(',');
		}

		tags.add(originalText);
		return tags;
	}

	public static String getLogText(Context context) {
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
		return sp.getString("log_text", "");
	}

	public static void setLogText(Context context, String text) {
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
		Editor editor = sp.edit();
		editor.putString("log_text", text);
		editor.commit();
	}

	/**
	 * 判断网络是否可用.
	 * 
	 * @param context
	 *            上下文
	 * @return true代表网络可用，false代表网络不可用.
	 */
	public static boolean isNetworkValid(Context context) {
		boolean result = false;
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			result = false;
		} else {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info == null) {
				result = false;
			} else {
				if (info.isAvailable()) {
					result = true;
				}
			}
		}
		return result;
	}

	/**
	 * 显示（时间是短暂的）土司消息
	 * 
	 * @param context
	 *            上下文
	 * @param msg
	 *            消息内容
	 */
	public static void showMsg(Context context, String msg) {
		if (context != null && msg != null) {
			Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 外部存储是否可写(也可读)，true代表可写，false代表不可写.
	 * 
	 * @return
	 */
	public static boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	@TargetApi(Build.VERSION_CODES.FROYO)
	private static String getExternalStoragePublicDirectory(String dirName) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), dirName);
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				return null;
			}
		}

		// Create a media file name
		String fileDir = mediaStorageDir.getPath();
		return fileDir;
	}

	/**
	 * 根据uri获取图片的真实路径.
	 * 
	 * @param activity
	 *            活动对象
	 * @param uri
	 *            uri
	 * @return 图片的真实路径
	 */
	public static String getPath(Activity activity, Uri uri) {
		String path=uri.getPath();
		try{
			String[] proj = { MediaColumns.DATA };
			// 好像是android多媒体数据库的封装接口，具体的看Android文档
			Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null);
			// 按我个人理解 这个是获得用户选择的图片的索引值
			int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
			// 将光标移至开头 ，这个很重要，不小心很容易引起越界
			cursor.moveToFirst();
			// 最后根据索引值获取图片路径
			path = cursor.getString(columnIndex);
		}catch(Exception e){
			//Uri是一个文件类型而不是一个多媒体类型，也就是说已file结尾而不是content结尾
		}
		return path;
	}

	/**
	 * 安全执行runnable的UI事件.
	 * 
	 * @param activity
	 * @param runnable
	 */
	public static void runOnUiThreadSafety(Activity activity,
			final Runnable runnable) {
		if (activity == null) {
			return;
		}
		if (runnable == null) {
			return;
		}
		activity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					runnable.run();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 关闭处理中的对话框.
	 * 
	 * @param progressDialog
	 *            处理对话框
	 */
	public static void clossDialog(Dialog dialog) {
		if (dialog != null && dialog.isShowing() && dialog.getWindow() != null) {
			dialog.dismiss();
		}
	}

	public static String getFileName(String filePath) {
		String fileName = null;
		if (!TextUtils.isEmpty(filePath)) {
			int lastBackslashIndex = filePath.lastIndexOf("/");
			if (lastBackslashIndex >= 0) {
				fileName = filePath.substring(lastBackslashIndex + 1);
			}
		}
		if (TextUtils.isEmpty(fileName)) {
			fileName = System.currentTimeMillis() + ".jpg";
		}
		return fileName;
	}

	public static void call(Context context, String phone) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_DIAL);
		intent.setData(Uri.parse("tel:" + phone));
		context.startActivity(intent);
	}

	public static String formatTwoFractionDigits(double d) {
		return formatFractionDigits(d, 2);
	}

	public static String formatFractionDigits(double d, int count) {
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(count);
		return nf.format(d);
	}
	
	public static String encode(String str) {
		try {
			str = URLEncoder.encode(str, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	public static void hideSoft(Context context) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public static void hideSoft(Context context, View view) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	/**
	 * dp转px
	 * 
	 * @param context
	 * @param dp
	 * @return
	 */
	public static float dp2px(Context context, float dp) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				metrics);
	}

	/**
	 * sp转px
	 * 
	 * @param context
	 * @param dp
	 * @return
	 */
	public static float sp2px(Context context, float sp) {
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp,
				metrics);
	}

}
